<template>
    <div style="width: 100%;">
        <!-- 搜索表单 -->
        <el-form :inline="true" ref="formRef" :model="formInline" class="demo-form-inline">
            <el-form-item label="姓名">
                <el-input v-model="formInline.staffName" placeholder="请输入姓名" clearable @change="formChange" />
            </el-form-item>
            <el-form-item label="职位">
                <el-select v-model="formInline.position" placeholder="请选择职位" clearable>
                    <el-option v-for="item in departments.positionList" :key="item.value" :label="item.label"
                        :value="item.label"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="发放时间">
                <el-date-picker style="width: 250px;" v-model="formInline.time" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>
            <el-form-item class="search">
                <el-button type="primary" :icon="Refresh" @click="resetFormInline">重置</el-button>
                <el-button type="primary" :icon="Search" @click="searchData">查询</el-button>
            </el-form-item>
        </el-form>
        <!-- 按钮组 -->
        <div class="btn-group">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button type="danger" @click="multipleDelete">删除</el-button>
        </div>
        <!-- 表格 -->
        <div class="table">
            <el-table :data="tableData" style="width: 100%" border height="420" show-overflow-tooltip
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" label="全选" />
                <el-table-column fixed label="索引" type="index" :index="indexMethod" align="center" width="55" />
                <el-table-column prop="send_time" label="发放时间" :formatter="formatDate" />
                <el-table-column prop="staff_no" label="工号" />
                <el-table-column prop="staff_name" label="姓名" />
                <el-table-column prop="position" label="职位" />
                <el-table-column prop="department_name" label="部门" />
                <el-table-column prop="base_pay" label="基本工资" />
                <el-table-column prop="net_salary" label="实发工资" />
                <el-table-column fixed="right" label="操作" width="180">
                    <template #default="scope">
                        <el-button type="primary" @click="handleDetail(scope.row)">详情</el-button>
                        <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <div class="pagination-wrapper">
            <el-pagination class="pagination" v-model:current-page="page.pageNum" v-model:page-size="page.pageSize"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="page.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 弹窗-新增 -->
        <el-dialog class="dialog" v-model="dialogVisibleAdd" title="新增" width="800" @close="handleCloseAdd">
            <el-form class="dialog-add-form" :inline="true" :model="dialogFormAdd" :rules="dialogFormAddRules"
                ref="dialogAddFormRef">
                <el-form-item label-width="120px" prop="staff_name" label="姓名">
                    <el-input v-model="dialogFormAdd.staff_name" placeholder="请输入" clearable @change="searchPosition" />
                </el-form-item>
                <el-form-item label-width="120px" prop="position" label="职位">
                    <el-select v-model="dialogFormAdd.position" placeholder="请选择" clearable>
                        <el-option v-for="position in departments.dialogPositionList" :key="position.value"
                            :label="position.label" :value="position.label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label-width="120px" prop="insurance" label="五险一金">
                    <el-input type="number" v-model="dialogFormAdd.insurance" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="全勤">
                    <el-input type="number" v-model="dialogFormAdd.full_attendance" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="绩效">
                    <el-input type="number" v-model="dialogFormAdd.achievements" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="加班">
                    <el-input type="number" v-model="dialogFormAdd.overtime_pay" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="生活补贴">
                    <el-input type="number" v-model="dialogFormAdd.living_allowance" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="旷工">
                    <el-input type="number" v-model="dialogFormAdd.absenteeism_fee" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="其他">
                    <el-input type="number" v-model="dialogFormAdd.other_deductions" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="备注">
                    <el-input style="width: 220px" v-model="dialogFormAdd.remarks" type="textarea" placeholder="请输入"
                        clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCloseAdd">取消</el-button>
                    <el-button type="primary" @click="handleAddSalary">
                        添加
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 弹窗-详情 -->
        <el-dialog class="dialog" v-model="dialogDetailVisible" title="详情" width="800" :close="handleDetailClose">
            <el-form class="dialog-form" :inline="true" :model="dialogDetailForm" ref="dialogDetailFormRef">
                <el-form-item label-width="120px" label="发放时间">
                    <el-input v-model="dialogDetailForm.send_time" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="工号">
                    <el-input v-model="dialogDetailForm.staff_no" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="姓名">
                    <el-input v-model="dialogDetailForm.staff_name" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="职位">
                    <el-input v-model="dialogDetailForm.position" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="部门">
                    <el-input v-model="dialogDetailForm.department_name" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="基本工资">
                    <el-input v-model="dialogDetailForm.base_pay" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="绩效">
                    <el-input v-model="dialogDetailForm.achievements" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="生活补贴">
                    <el-input v-model="dialogDetailForm.living_allowance" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="全勤">
                    <el-input v-model="dialogDetailForm.full_attendance" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="加班">
                    <el-input v-model="dialogDetailForm.overtime_pay" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="五险一金">
                    <el-input v-model="dialogDetailForm.insurance" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="旷工">
                    <el-input v-model="dialogDetailForm.absenteeism_fee" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="其它">
                    <el-input v-model="dialogDetailForm.other_deductions" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="实发工资">
                    <el-input v-model="dialogDetailForm.net_salary" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="备注">
                    <el-input v-model="dialogDetailForm.remarks" clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDetailClose">关闭</el-button>
                    <el-button type="primary" @click="updateDetailDialog">
                        修改
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { queryDepartments } from '@/api/department'
import { timeProcessing } from '@/utils/date'
import { querySalary, addSalary, delSalary, queryEmployees, updateSalary } from '@/api/employee';

// 分页
const page = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0,
})

// 部门和职位
const departments = reactive({
    departmentList: [],
    positionList: [],
    dialogPositionList: []
})

// 表单-搜索-数据
const formInline = reactive({
    staffName: '',
    position: '',
    time: null,
})

// 表格数据
const tableData = ref([])

// 多选-id
const ids = ref([]);

// 新增-弹窗
const dialogVisibleAdd = ref(false)
const dialogAddFormRef = ref(null)
const dialogFormAdd = reactive({})
const dialogFormAddRules = {
    staff_name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    position: [
        { required: true, message: '请选择职位', trigger: 'blur' },
    ],
    base_pay: [
        { required: true, message: '请输入基本工资', trigger: 'blur' },
    ],
    insurance: [
        { required: true, message: '请输入五险一金', trigger: 'blur' },
    ],
}

// 详情-弹窗
const dialogDetailVisible = ref(false)
const dialogDetailFormRef = ref(null)
const dialogDetailForm = reactive({})

const positionListClone = ref(null);

// 索引
const indexMethod = (index) => {
    return page.pageSize * (page.pageNum - 1) + index + 1
}

// 表格多选
const handleSelectionChange = (val) => {
    ids.value = val.map(item => item.id);
}

const formatDate = (row, column, cellValue) => {
    return timeProcessing(cellValue, 'date')
}

// 获取部门和职位
const getDepartments = async () => {
    try {
        const res = await queryDepartments();
        if (res.code === 0) {
            const departmentSet = new Set(departments.departmentList.map(d => d.label));
            res.data.list.forEach(item => {
                if (!departmentSet.has(item.department_name)) {
                    departments.departmentList.push({
                        value: item.department_name,
                        label: item.department_name
                    });
                    departmentSet.add(item.department_name);
                }
                departments.positionList.push({
                    value: item.id,
                    label: item.position
                });
            });
            positionListClone.value = departments.positionList;
        } else {
            ElMessage.error(res.msg);
        }
    } catch {
        console.log("请求失败");
    }
}

// 重置
const resetFormInline = () => {
    formInline.staffName = '';
    formInline.position = '';
    formInline.time = null;
    searchData();
}

const formChange = async (value) => {
    formInline.position = null;
    if (value) {
        const res = await queryEmployees({ staffName: value });
        if (res.code === 0) {
            departments.positionList = [];
            res.data.list.map(item => {
                departments.positionList.push({
                    value: item.id,
                    label: item.position
                });
            })
        }
    } else {
        departments.positionList = positionListClone.value;
    }
}

const searchPosition = async (value) => {
    if (value) {
        const res = await queryEmployees({ staffName: value });
        departments.dialogPositionList = [];
        res.data.list.map(item => {
            departments.dialogPositionList.push({
                value: item.id,
                label: item.position
            });
        })
    } else {
        departments.dialogPositionList = [];
    }
}

// 搜索
const searchData = async () => {
    const data = {
        staffName: formInline.staffName,
        position: formInline.position,
        sendTimeStart: formInline.time ? formInline.time[0] : '',
        sendTimeEnd: formInline.time ? formInline.time[1] : '',
        pageNum: page.pageNum,
        pageSize: page.pageSize,
    }
    try {
        const res = await querySalary(data);
        if (res.code === 0) {
            tableData.value = res.data.list;
            page.total = res.data.total;
        } else {
            // ElMessage.error(res.msg);
        }
    } catch {
        console.log("请求失败");
    }
}

// 计算实发工资
const computePay = (base_pay) => {
    let net_salary = Number(base_pay) -
        Number(dialogFormAdd.insurance) +
        Number(dialogFormAdd.full_attendance) +
        Number(dialogFormAdd.achievements) +
        Number(dialogFormAdd.overtime_pay) +
        Number(dialogFormAdd.living_allowance) -
        Number(dialogFormAdd.absenteeism_fee) +
        Number(dialogFormAdd.other_deductions);
    return net_salary;
}

// 新增
const handleAddSalary = () => {
    if (dialogAddFormRef.value) {
        dialogAddFormRef.value.validate(async (valid) => {
            if (!valid) return;
            const queryEmployeeData = {
                staffName: dialogFormAdd.name,
                position: dialogFormAdd.position,
            }
            const addData = {
                ...dialogFormAdd,
                send_time: timeProcessing(new Date(), 'date'),
            }
            try {
                const res = await queryEmployees(queryEmployeeData);
                const employeeInfo = res.data.list[0];
                addData.staff_no = employeeInfo.staff_no;
                addData.department_name = employeeInfo.department_name;
                addData.base_pay = employeeInfo.base_pay;
                addData.net_salary = computePay(addData.base_pay);
                const resAdd = await addSalary(addData);
                if (resAdd.code === 0) {
                    ElMessage.success('新增成功！');
                    handleCloseAdd();
                    searchData();
                } else {
                    ElMessage.error('新增失败！');
                }
            } catch {
                console.log("请求失败");
            }
        })
    }
}

// 删除
const handleDelete = (ids) => {
    const data = Array.isArray(ids) ? ids : [ids];
    ElMessageBox.confirm('确认删除选中项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await delSalary(data);
            if (res.code === 0) {
                ElMessage.success('删除成功！');
                searchData();
            } else {
                ElMessage.error('删除失败！');
            }
        } catch {
            console.log("请求失败");
        }
    }).catch(() => {
        console.log('取消删除');
    })
}

// 多选删除
const multipleDelete = () => {
    if (ids.value.length === 0) {
        ElMessage.warning('请选择要删除的员工！');
        return
    }
    handleDelete(ids.value)
}

// 修改
const updateDetailDialog = async () => {
    const data = {
        id: dialogDetailForm.id,
        remarks: dialogDetailForm.remarks,
    }
    try {
        const res = await updateSalary(data);
        if (res.code == 0) {
            ElMessage.success('修改成功！');
            handleDetailClose();
            searchData();
        } else {
            ElMessage.error('修改失败！');
        }
    } catch {
        console.log("请求失败");
    }
}

// 新增-弹窗-打开
const handleAdd = () => {
    dialogVisibleAdd.value = true;
    departments.dialogPositionList = [];
}

// 新增-弹窗-关闭
const handleCloseAdd = () => {
    dialogVisibleAdd.value = false;
    if (dialogAddFormRef.value) dialogAddFormRef.value.resetFields();
    // 清空旧数据
    Object.keys(dialogFormAdd).forEach(key => {
        dialogFormAdd[key] = '';
    });
}

// 详情-弹窗-打开
const handleDetail = (row) => {
    dialogDetailVisible.value = true;
    dialogDetailForm.id = row.id;
    dialogDetailForm.send_time = row.send_time;
    dialogDetailForm.staff_no = row.staff_no;
    dialogDetailForm.staff_name = row.staff_name;
    dialogDetailForm.position = row.position;
    dialogDetailForm.department_name = row.department_name;
    dialogDetailForm.base_pay = row.base_pay;
    dialogDetailForm.achievements = row.achievements;
    dialogDetailForm.living_allowance = row.living_allowance;
    dialogDetailForm.full_attendance = row.full_attendance;
    dialogDetailForm.overtime_pay = row.overtime_pay;
    dialogDetailForm.insurance = row.insurance;
    dialogDetailForm.absenteeism_fee = row.absenteeism_fee;
    dialogDetailForm.other_deductions = row.other_deductions;
    dialogDetailForm.net_salary = row.net_salary;
    dialogDetailForm.remarks = row.remarks;
}

// 详情-弹窗-关闭
const handleDetailClose = () => {
    dialogDetailVisible.value = false
    if (dialogDetailFormRef.value) dialogDetailFormRef.value.resetFields();
}

// 分页
const handleSizeChange = (val) => {
    page.pageSize = val
    searchData()
}

const handleCurrentChange = (val) => {
    page.pageNum = val
    searchData()
}

onMounted(() => {
    searchData();
    getDepartments();
})
</script>

<style lang="scss" scoped>
.demo-form-inline {
    padding: 10px 20px 0;
}

.demo-form-inline .el-input {
    --el-input-width: 150px;
}

.demo-form-inline .el-select {
    --el-select-width: 150px;
}

.btn-group {
    box-sizing: border-box;
    padding-right: 20px;
    margin-bottom: 5px;
    margin-top: -15px;
    float: right;
}

.table {
    box-sizing: border-box;
    padding: 0 20px 0 15px;
}

.footer {
    position: relative;
    width: 100%;
    height: auto;
}

.pagination-wrapper {
    width: 100%;
    height: 44px;
    display: flex;
    justify-content: flex-end;
}

.pagination {
    margin-top: 15px;
    margin-right: 20px;
}

:deep(.el-dialog__body) {
    display: flex;
    justify-content: center;
}

.dialog-form {
    .el-input {
        --el-input-width: 220px;
    }
}

.avatar-uploader .el-upload {
    border: 1px dashed #8c939d;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: none;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.dialog-add-form {
    .el-input {
        --el-input-width: 220px;
    }

    .el-select {
        --el-select-width: 220px;
    }
}
</style>